<template>
  <div ref="chartRef" class="chart-container"></div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'NightingaleChart',
  props: {
    data: {
      type: Array,
      required: true,
      validator: (value) =>
      {
        return value.every(item => 'value' in item && 'name' in item)
      }
    },
    name: {
      type: String,
      required: true
    }
  },
  data()
  {
    return {
      chart: null
    }
  },
  methods: {
    initChart()
    {
      this.chart = echarts.init(this.$refs.chartRef)

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: function(params)
          {
            return `${params.seriesName}<br>${params.name}: ${params.value}`
          }
        },
        legend: {
          show: false
        },
        toolbox: {
          show: true,
          feature: {
            mark: { show: true },
            saveAsImage: { show: true }
          }
        },
        series: [
          {
            name: this.name,
            type: 'pie',
            radius: [50, 150],
            center: ['50%', '50%'],
            roseType: 'area',
            itemStyle: {
              borderRadius: 8
            },
            data: this.data // 使用传入的 props 数据
          }
        ]
      }

      this.chart.setOption(option)
    }
  },
  watch: {
    // 监听 data 的变化，动态更新图表
    data: {
      deep: true,
      handler()
      {
        if (this.chart)
        {
          this.chart.setOption({
            series: [
              {
                data: this.data
              }
            ]
          })
        }
      }
    }
  },
  mounted()
  {
    this.initChart()
  },
  beforeUnmount()
  {
    if (this.chart)
      this.chart.dispose()
  }
}
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
}
</style>
